<?php

namespace control;
/*
*生产液氨记录
*/
class produceLnLogClass extends adIndexClass
{
    private const page = 'produceLnLog'; # 权限
    private const table = 'steel_cylinder_detail'; # 数据表
    private const title = '生产液氨记录';

    /**
     * 字段初始化
     */
    public function fieldInit(): array
    {
        $tr = [
            'barcode'         => [
                'name'  => '内部编码',
                'width' => 200,
            ],
            'code' => [
                'name'  => '出厂码',
                'width' => 200,
                'sort' => 1,
            ],
            'weight'  => [
                'name'  => '重量（KG）',
                'width' => 200,
            ],
            'log_time'          => [
                'name'  => '充装时间',
                'width' => 150,
                'sort' => 1,
            ],

        ];
        return $tr;
    }


    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    '内部编码'   => text(array("name" => "barcode")),
                    '出厂码'   => text(array("name" => "code")),
                ],
                [
                    "日期" => text(array("name" => "time", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ],
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*生产液氨入口页*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
//        if ($this->power(self::page, "edit")) {
//            $button .= "<span class='spanButton' onclick=\"layer('" . self::page . "','edit',$('form[name=listForm]').serialize())\">入库</span>\n";
//        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*生产液氨列表*/
    public function homeSearch()
    {
        //查询结果
        $where = ' 1=1 ';
        $equal = [
//            'barcode' => $this->post('barcode'),
//            'code' => $this->post('code'),
            'coid'=>self::$coid,
        ];
        //生成查询语句
        $where .= search([
            "=" => $equal,
        ]);
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'log_time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        $and = "";
        if ($this->post('time')) {
            $and .= self::timeComparison($this->post('time'), field: "log_time");
        }
        if($this->post('code')){
            $and = " and steelCylinderId in (SELECT id FROM steel_cylinder WHERE code like '%".$this->post('code')."%')  ";
        }
        if($this->post('barcode')){
            $and = " and steelCylinderId in (SELECT id FROM steel_cylinder WHERE barcode like '%".$this->post('barcode')."%')  ";
        }
        $page = $this->page(["table" => self::table, "where" => $where." and (jsonData->'$.N_AFTER' > 0) ".$and, "order" => $orderBy['orderBy']]);
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        $url = root . "control/adIndex.html?cla=" . self::page;
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = [
                "box" => ["name" => "listId", "value" => $array['id']],
            ];
            $liButton[] = $this->dominate($dominate) . hidden(["name" => "cylinderId", "value" => $array['id']]);
            $info = query('steel_cylinder',"id='$array[steelCylinderId]'");
            $jsonData = json_decode($array['jsonData'],true);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "barcode":
                        $row[] = $info['barcode'];
                        break;
                    case "code":
                        $row[] = $info['code'];
                        break;
                    case "weight":
                        $row[] = $jsonData['N_AFTER'] ?: $jsonData['N_BEFORE'] ;
                        break;
                    case "log_time":
                        $row[] = $jsonData['DT_ADD_END'];
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = "<form name='listForm'>" . $li . "</form>" . $page['button'] .clear;
        return json_encode($json, 320);
    }

    /**
     * 导出
     */
    public function exportData()
    {
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        }  else {
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = find(array(
                    "table" => self::table,
                    "where" => " coid='".self::$coid."' and id in ('".implode("','",$checkedId)."') order by time desc",
                ))['array'];
            }else{
                $sql   = $_SESSION[self::page]['sql'];
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                $info = query('steel_cylinder',"id='$array[steelCylinderId]'");
                $jsonData = json_decode($array['jsonData'],true);
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '内部编码'=>$info['barcode'],
                            '出厂码'=>$info['code'],
                            '重量（KG）'=>$jsonData['N_AFTER'] ?: $jsonData['N_BEFORE'],
                            '充装时间'=>$jsonData['DT_ADD_END'],
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }
            $text = $this->control['name'] . "导出了生产液氨记录表";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, "生产液氨记录表.xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));

    }

    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'内部编码',
                    'aliasName'=>'内部编码',//barcode
                ],
                [
                    'columnName'=>'出厂码',//code
                    'aliasName'=>'出厂码',
                ],
                [
                    'columnName'=>'重量（KG）',//model
                    'aliasName'=>'重量（KG）',
                ],
                [
                    'columnName'=>'充装时间',//vc_node
                    'aliasName'=>'充装时间',
                ],
            ]
        };
    }
}
